#pragma once
#include <iostream>
#include "Sock.hpp"

typedef std::function<void(int)> func_t;
class Httpserver
{
public:
    Httpserver(const uint16_t& port,func_t func)
        :_port(port),_func(func)
    {
        _listensock = sock.Socket();
        sock.Bind(_listensock,_port);
        sock.Listen(_listensock);
    }

    void Start()
    {
        signal(SIGCHLD,SIG_IGN);
        while (true)
        {
            std::string clientIP;
            uint16_t clientPort;
            int sockfd = sock.Accept(_listensock,&clientIP,&clientPort);
            if(sockfd < 0) continue;
            if(fork() ==  0)
            {
                close(_listensock);
                _func(sockfd);
                close(sockfd);
                exit(1);
            }
            close(sockfd);
        }
        
    }
    ~Httpserver()
    {
        if(_listensock >= 0)
        {
            close(_listensock);
        }
    }

private:
    Sock sock;
    int _listensock;//套接字
    uint16_t _port;//端口号
    func_t _func;
};
